# -*- coding: utf-8 -*-
from mutagen.easyid3 import EasyID3
from mutagen.id3 import ID3
from mutagen.mp3 import MP3

from Exceptions.TagReaderException import TagReaderException

"""
Liest die Meta-Daten aus MP3-Dateien ein. Wird im Normalfall über die Wrapper-
Klasse TagReader.Reader aufgerufen.

@author: Philipp Dermitzel
@date: 2011-03-31
@version: 1.4.0
"""
class Mp3Reader(object):
    
    """
    ----------------------------------------------------------------------------
    Konstruktor
    ----------------------------------------------------------------------------
    """
    
    """
    Der Konstruktor. Wirft TagReaderExceptions!
    @param path: Der Pfad zur (Audio-)Datei.
    @type path: String
    """
    def __init__(self, path):
        """
        Der Pfad zur (Audio-)Datei.
        @type: String
        """
        self.__pathToFile = None
    
        """
        Mutagen-Audio-Handle, in welchem die Meta-Daten gespeichert werden.
        @type: unknown
        """
        self.__audioHandle = None
 
        """
        Mutagen-Audio-Handle, in welchem Datei-Informationen gespeichert werden.
        @type: unknown
        """
        self.__mp3Handle = None
    
        """
        Mutagen-ID3-Handle, in welchem die gesamten ID3-Tags gespeichert werden.
        @type: unknown
        """
        self.__id3Handle = None
    
        """
        Die benötigten Meta-Daten.
        @type: Dictionary
        """   
        self.__tagData = {
            'title'     : None,
            'artist'    : None,
            'trackOnCd' : None,
            'cd'        : None,
            'year'      : None,
            'length'    : None,
            'artistMbId': None,
            'cdMbId'    : None,
            'genres'    : None,
            'sort'      : None
        }
        
        if isinstance(path, str):
            self.__pathToFile = path
            self.__mp3Handle = MP3(self.__pathToFile)
            try:
                self.__audioHandle = EasyID3(self.__pathToFile)
                self.__id3Handle = ID3(self.__pathToFile)
                self.__setTagData()
            except:
                print "Kein ID3-Tag bei %s" %(path)    
                self.__tagData['length'] = int(self.__mp3Handle.info.length) 
        else: raise TagReaderException("Kein Pfad zur Audio-File angegeben")
    
    """
    ----------------------------------------------------------------------------
    Getter und Setter
    ----------------------------------------------------------------------------
    """
    
    """
    Getter.
    @return: Der Pfad zur (Audio-)Datei.
    @rtype: String
    """        
    def getPathToFile(self):
        return self.__pathToFile
    
    """
    Getter.
    @return: Die Meta-Daten der Datei.
    @rtype: Dictionary
    """
    def getTagData(self):
        return self.__tagData
    
    """
    ----------------------------------------------------------------------------
    Methoden der Klasse
    ----------------------------------------------------------------------------
    """
    
    """
    Hauptmethode. Liest die Meta-Daten der Datei ein und speichert sie im 
    Klassen-Dictionary. Wirft TagReaderExceptions!
    """        
    def __setTagData(self):
        if (self.__audioHandle is None or self.__mp3Handle is None):
            raise TagReaderException("Kein Audio/MP3-Handle erzeugt bei %s" 
                %(self.__pathToFile))
        else:
            try: 
                self.__tagData['title'] = str(self.__audioHandle['title'][0])
            except: pass
            try: 
                self.__tagData['artist'] = str(self.__audioHandle['artist'][0])
            except: pass
            try: 
                self.__tagData['cd'] = str(self.__audioHandle['album'][0])
            except: pass
            try: 
                self.__tagData['year'] = int(self.__audioHandle['date'][0][0:4])
            except: pass
            try: 
                self.__tagData['sort'] = str(self.__id3Handle['TSOP'])
            except: pass
            try: 
                self.__tagData['genres'] = []
                for genre in self.__audioHandle['genre']:
                    self.__tagData['genres'].append(str(genre))
            except: self.__tagData['genres'] = None
            self.__tagData['length'] = int(self.__mp3Handle.info.length)
            try :
                if self.__audioHandle['tracknumber'][0].find('/') > -1:
                    parts = self.__audioHandle['tracknumber'][0].split('/')
                    self.__tagData['trackOnCd'] = int(parts[0])
                else: 
                    self.__tagData['trackOnCd'] = int(
                        self.__audioHandle['tracknumber'][0])
            except: self.__tagData['trackOnCd'] = None            
